/*
 * Description:
 * 用来缓存一个调用，当调用返回时会找到相应的调用存入返回值，并且唤醒。
 */
#include <iostream>
#include <windows.h>

#include "log.h"
#include "call_record.h"

namespace COMMON {
CallRecord::CallRecord(google::protobuf::MessageLite *res) : m_result(res)
{
}

CallRecord::~CallRecord()
{
    while (m_isWait) {
        Sleep(5); /* 5 等待5ms,保证锁退出 */
    }
}

void CallRecord::WaitForResponse()
{
    std::unique_lock<std::mutex> lk(m_mutex);
    while (!m_isWoken) {
        m_isWait = true;
        m_cv.wait(lk);
        m_isWait = false;
    }
}

void CallRecord::WakeUp()
{
    std::unique_lock<std::mutex> lk(m_mutex);
    m_isWoken = true;
    m_cv.notify_all();
}

void CallRecord::SetResult(const Guest::protobuf::link::Result &result)
{
    m_errorCode = -1;
    if (m_result == nullptr) {
        LOG_ERR("m_result is nullptr");
        return;
    }
    if (!m_result->ParseFromString(result.response())) {
        LOG_ERR("response parse from protobuf error");
    } else {
        m_errorCode = result.errorcode();
    }
}

int CallRecord::GetErrorCode() const
{
    // 当前设计为result.errorcode()直接透传给业务自行处理，通信层只返回成功。
    return OK;
}
}
